# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# File       : logout_view.py
# Time       ：2023/10/21 15:38
# Author     ：author name
# version    ：python 3.10
# Description：检查token是否过期
"""
from flask_restx import fields

from apis.token import token_ns
from public.api_utils.api_decorator import handle_api_error
from public.api_utils.jwt_utils import JWTUtils
from public.base_response import MarshalModel, generate_response
from public.base_view import AbstractView
from public.logger import logger

token_model = {'token': fields.String()}
token_marshal = MarshalModel('check_token', token_ns)


class CheckTokenView(AbstractView):
    url = '/check'

    def __init__(self, *args, **kwargs):
        super(CheckTokenView, self).__init__(*args, **kwargs)
        self.token = self.form_data.get('token')
        self.jwt_utils = JWTUtils()

    @handle_api_error()
    @token_ns.expect(token_marshal.detail_request(token_model))
    @token_ns.marshal_with(token_marshal.detail_response(token_model, is_db=False))
    def get(self):
        try:
            self.jwt_utils.verify_token(self.token)
        except Exception as e:
            logger.error(f'token 过期:{e}')
            self.token = JWTUtils().refresh_token(self.token)
        return generate_response(data={'token': self.token})
